import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/widgets.dart';
import 'details.dart';
// import 'photos.dart';
import 'package:share_plus/share_plus.dart';
import 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:whatsapp_share/whatsapp_share.dart';
import 'package:image_picker/image_picker.dart';
import 'ads/consent_manager.dart';
import 'package:morningqs/ads/ads_unit_id.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:skeletonizer/skeletonizer.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'common/loading_spinner.dart'; // 导入公共组件
import 'common/api_service.dart'; // 导入 ApiService 类
import 'package:cached_network_image/cached_network_image.dart'; //网络图片缓存到本地

class ClassificationListPage extends StatefulWidget {
  final Map<String, dynamic> classificationItem;
  const ClassificationListPage({
    super.key,
    required this.classificationItem,
  });

  @override
  State<ClassificationListPage> createState() => _MyTextPageState();
}

class _MyTextPageState extends State<ClassificationListPage> {
  bool isMember = false;
  final _consentManager = ConsentManager.instance;
  // bool _isLoaded = false;
  // BannerAd? _bannerAd;

  InterstitialAd? _interstitialAd;

  Map<String, dynamic> classificationItem = {};
  List dataList = []; // 类别数据

  // final ScrollController _scrollController = ScrollController();
  List<int> favoriteList = [];
  List recommendImgs = [];

  static const _insets = 12.0;
  BannerAd? _inlineAdaptiveAd;
  bool _isLoaded = false;
  AdSize? _adSize;
  // late Orientation _currentOrientation;
  double get _adWidth => MediaQuery.of(context).size.width - (2 * _insets);


  _saveIntList(favoriteList) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setStringList('favoriteList', favoriteList);
  }

  Future<List<String>> _getIntList() async {
    final prefs = await SharedPreferences.getInstance();
    List<String> favoriteList = prefs.getStringList('favoriteList') ?? [];
    return favoriteList;
  }

  Future<int> _getAdStatus() async {
    final prefs = await SharedPreferences.getInstance();
    int status = prefs.getInt('inlineAdStatus') ?? 1;
    return status;
  }


  void _loadInlineAd() async {
    int adStatus = await _getAdStatus();
    if (adStatus != 1) {
      return;
    }

    await _inlineAdaptiveAd?.dispose();
    setState(() {
      _inlineAdaptiveAd = null;
      _isLoaded = false;
    });

    // Get an inline adaptive size for the current orientation.
    AdSize size = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(
        _adWidth.truncate());

    _inlineAdaptiveAd = BannerAd(
      // TODO: replace this test ad unit with your own ad unit.
      adUnitId: AdsUnitId.inlineAdaptive,
      size: size,
      request: AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) async {
          // print('Inline adaptive banner loaded: ${ad.responseInfo}');

          // After the ad is loaded, get the platform ad size and use it to
          // update the height of the container. This is necessary because the
          // height can change after the ad is loaded.
          BannerAd bannerAd = (ad as BannerAd);
          final AdSize? size = await bannerAd.getPlatformAdSize();
          if (size == null) {
            print('Error: getPlatformAdSize() returned null for $bannerAd');
            return;
          }

          setState(() {
            _inlineAdaptiveAd = bannerAd;
            _isLoaded = true;
            _adSize = size;
          });
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('Inline adaptive banner failedToLoad: $error');
          ad.dispose();
        },
      ),
    );
    await _inlineAdaptiveAd!.load();
  }

  Widget _getAdWidget() {
    return OrientationBuilder(
      builder: (context, orientation) {
        if (
            _inlineAdaptiveAd != null &&
            _isLoaded &&
            _adSize != null) {
          return Align(
              child: Container(
                // margin: const EdgeInsets.only(top: 12),
            width: _adWidth,
            height: _adSize!.height.toDouble(),
            child: AdWidget(
              ad: _inlineAdaptiveAd!,
            ),
          ));
        }
        // Reload the ad if the orientation changes.
        // if (_currentOrientation != orientation) {
        //   _currentOrientation = orientation;
        //   _loadAd();
        // }
        return Container();
      },
    );
  }

  // Future<int> _getAdStatus() async {
  //   final prefs = await SharedPreferences.getInstance();
  //   int status = prefs.getInt('bannerAdStatus') ?? 1;
  //   return status;
  // }

  // Future<int> _getInsertAdStatus() async {
  //   final prefs = await SharedPreferences.getInstance();
  //   int status = prefs.getInt('insertAdStatus') ?? 1;
  //   return status;
  // }
  
  // void loadInsertAd() async {
  //   int adStatus = await _getInsertAdStatus();
  //   if (adStatus != 1) {
  //     return;
  //   }
  //   // Only load an ad if the Mobile Ads SDK has gathered consent aligned with
  //   // the app's configured messages.
  //   var canRequestAds = await _consentManager.canRequestAds();
  //   if (!canRequestAds) {
  //     return;
  //   }

  //   InterstitialAd.load(
  //       adUnitId: AdsUnitId.insertAdUnitId,
  //       request: const AdRequest(),
  //       adLoadCallback: InterstitialAdLoadCallback(
  //         // Called when an ad is successfully received.
  //         onAdLoaded: (ad) {
  //           debugPrint('$ad loaded.');
  //           // Keep a reference to the ad so you can show it later.
  //           _interstitialAd = ad;
  //         },
  //         // Called when an ad request failed.
  //         onAdFailedToLoad: (LoadAdError error) {
  //           debugPrint('InterstitialAd failed to load: $error');
  //         },
  //       ));
  // }


  @override
  Future<void> getFavoriteList() async {
    List<String> favoriteList = await _getIntList();

    List<int> likeList = [];
    for(int item in classificationItem['sort']){
      if(favoriteList.contains(item.toString())){
        likeList.add(1);
      }else{  
        likeList.add(0);
      }
    }
    setState(() {
      favoriteList = favoriteList;
      classificationItem['likeList'] = likeList;
    });

  }

  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  Future<void> _logScreenView(classificationItem) async {
    await analytics.logScreenView(
      screenName: classificationItem['slug'],
      screenClass: '${classificationItem['slug']}ClassificationPage_ES',
    );
  }

  @override
  void initState() {
    super.initState();
    _loadInlineAd();

    setState(() {
      classificationItem = widget.classificationItem;
      classificationItem['likeList'] = [];
    });
    _logScreenView(classificationItem);
    // print(classificationItem)
    getFavoriteList();
    
  }


  @override
  void dispose() {
    _inlineAdaptiveAd?.dispose();
    // _interstitialAd?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var sizewidth = MediaQuery.of(context).size.width;
    var bottomHeight = MediaQuery.of(context).padding.bottom;
    final controller = ScrollController();
    
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 255, 255, 255),
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(60),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.15),
                offset: const Offset(0, 2),
                blurRadius: 6.0,
              ),
            ],
          ),
          child: AppBar(
            backgroundColor: Colors.white,
            // iconTheme: const IconThemeData(color: Colors.white),
            title: Text(
              widget.classificationItem['category'],
              style:
                  const TextStyle(fontFamily: 'OpenSans', color: Colors.black, fontWeight: FontWeight.bold),
            ),
            elevation: 0,
            // leading: IconButton(
            //   icon: const Icon(CupertinoIcons.back),
            //   onPressed: () {
            //     Navigator.of(context).pop('isFavorite');
            //   },
            // ),
            // leading: IconButton(
            //   icon: const Icon(CupertinoIcons.back),
            //   onPressed: () {
            //     Navigator.of(context).pop('isFavorite');
            //     if(!isMember){
            //       _interstitialAd?.show();
            //     }
                
            //   },
            // ),
            
          ),
        ),
      ),
      body: Stack(
        children: [
          if(classificationItem['sort'].isNotEmpty && classificationItem['gif'].isNotEmpty && classificationItem['likeList'].isNotEmpty)
          Padding(
            // bottom: bottomHeight+86
            padding:
                 EdgeInsets.only(top: 10, left: 10, right: 10, ),
            child: SingleChildScrollView(
              controller: controller,
              child: Align(
                alignment: Alignment.topLeft,
                child: Wrap(
                  spacing: 10.0,
                  runSpacing: 10.0,
                  children: [
                    for (int index = 0; index < classificationItem['sort'].length; index++)...[
                      Recommend(
                        imgId: classificationItem['sort'][index],
                        sizewidth: sizewidth,
                        gif: classificationItem['gif'][index], // 使用当前索引
                        like: classificationItem['likeList'][index],
                      ),
                      if (index == 1) 
                        _getAdWidget(), // 替换为你的广告组件
                    ]
                  ],
                ),
              ),
            ),
          ),
          // Positioned(
          //     bottom: 0, 
          //     right: 0, 
          //     left: 0,
          //     child: Container(
          //       padding: const EdgeInsets.only(top: 16),
          //       height: bottomHeight+86,
          //       color: Colors.white,
          //       // child: _bannerAd != null && _isLoaded ? Container(child: Text(_bannerAd!.size.height.toString()),) : Container(),
          //       child: SafeArea(
          //         child: _bannerAd != null && _isLoaded ? SizedBox(
          //           width: _bannerAd!.size.width.toDouble(),
          //           height: 70,
          //           child: AdWidget(ad: _bannerAd!),
          //       ) : const Skeletonizer.zone(
          //           child: ListTile(
          //               title: Bone.text(words: 2),
          //               subtitle: Bone.text(),
          //               trailing: Bone.button(), 
          //             ),
                    
          //       )
          //     ),
          //   )
          //   ),
          // if(_bannerAd == null)
          //   Positioned(
          //     right: 12,
          //     bottom: bottomHeight+50,
          //     child: Container(
          //       width: 32,
          //       height: 20,
          //       decoration: BoxDecoration(
          //         borderRadius: BorderRadius.circular(4),
          //         color: Colors.black,
          //       ),
                
          //       child: const Center(
          //         child: Text('Ad', style: TextStyle(color: Colors.white, fontSize: 12),),
          //       ) 
          //     )
          //   )
        ],
      ) 
    );
  }
}

class Recommend extends StatefulWidget {
  final int imgId;
  final double sizewidth;
  final int gif;
  final int like;

  const Recommend({
    super.key,
    required this.imgId,
    required this.sizewidth,
    required this.gif,
    required this.like
  });
  @override
  State<Recommend> createState() => RecommendAssembly();
}

class RecommendAssembly extends State<Recommend> {
  List<String> favoriteList = [];
  int imgId = 0;
  int gif = 0;
  int like = 0;

  final _MyTextPageState _aInstance = _MyTextPageState();

  void _logFavoriteEvent(String itemId) async {
    await FirebaseAnalytics.instance.logEvent(
      name: "favorite_image",
      parameters: {
          // "content_type": "image",
          "image_id": itemId,
      },
    );
  }

  @override
  void initState() {
    super.initState();

    setState(() {
      imgId = widget.imgId;
      gif =  widget.gif;
      like = widget.like;
    });

  }


  Future<void> shareAssetImage(String assetName) async {
    try {
      final bytes = await rootBundle.load(assetName);
      final tempDir = await getTemporaryDirectory();
      final tempFile = File('${tempDir.path}/shared_image.jpg');
      await tempFile.writeAsBytes(bytes.buffer.asUint8List());
      await Share.shareXFiles(
        [XFile(tempFile.path)],
        text: 'Please review the shared images',
        sharePositionOrigin: const Rect.fromLTWH(0, 0, 100, 100),
        subject: 'Shared Image',
      );
    } catch (e) {
      print('Error sharing asset image: $e');
    }
  }

  // Future<void> shareFileToWhatsApp(String assetName, String phone) async {
  //   try {
  //     final bytes = await rootBundle.load(assetName);
  //     final tempDir = await getTemporaryDirectory();
  //     final tempFile = File('${tempDir.path}/shared_image.jpg');
  //     await tempFile.writeAsBytes(bytes.buffer.asUint8List());
  //     await WhatsappShare.shareFile(
  //       phone: phone,
  //       filePath: [tempFile.path],
  //     );
  //   } catch (e) {
  //     print('Error sharing asset image: $e');
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    // recommendImgItem = widget.recommendImgItem;
    // String photourl = recommendImgItem['imgurl'];
    // int gif = recommendImgItem['gif'];
    // print(recommendImgItem['gif']);
    return Padding(
      padding: const EdgeInsets.all(0),
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => DetailPage(imgId: imgId, gif: gif),
            ),
          );
        },
        child: Stack(
          children: [
            Container(
              width: (widget.sizewidth - 30) / 2,
              height: (widget.sizewidth - 30) / 2,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child:CachedNetworkImage(
                  imageUrl: 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/images/$imgId.${gif==0?'webp?x-oss-process=image/resize,p_40':'gif'}',
                  placeholder: (context, url) => const LoadingSpinner(), // 占位图
                  errorWidget: (context, url, error) => const Icon(Icons.error), // 错误图标
                  fit: BoxFit.cover,
                )
              ),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8),
                  ),
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomLeft,
                    colors: [
                      Color.fromRGBO(0, 0, 0, 0),
                      Color.fromRGBO(0, 0, 0, 0.5)
                    ],
                  ),
                ),
                height: 80,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () async {
                        List<String> favoriteList =
                            await _aInstance._getIntList();
                        setState(() {
                          String itemId = imgId.toString();
                          if (favoriteList.contains(itemId)) {
                            favoriteList.remove(itemId);
                            like = 0;
                          } else {
                            
                            favoriteList.add(itemId);
                            like = 1;
                            _logFavoriteEvent(itemId);
                          }
                        });
                        print(favoriteList);
                        await _aInstance._saveIntList(favoriteList);
                      },
                      child: Icon(
                        Icons.favorite,
                        size: 28,
                        color: like == 1
                            ? const Color.fromARGB(255, 252, 229, 13)
                            : Colors.white,
                      ),
                    ),
                    // GestureDetector(
                    //   onTap: () async {
                    //     await shareAssetImage(photourl);
                    //   },
                    //   child: const Icon(
                    //     Icons.share,
                    //     size: 28,
                    //     color: Colors.white,
                    //   ),
                    // ),
                  ],
                ),
              ),
            ),
            if(gif == 1)
            Positioned(
              left: 5,
              top: 5,
              child: Container(
                width: 36,
                height: 28,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(18),
                  color: const Color.fromRGBO(255, 255, 255, .7),
                ),
                child: const Center(
                  child: Text('GIF',style: TextStyle( fontSize: 14),),
                ),
              )
            ),
          ],
        ),
      ),
    );
  }
  
  
}
